package Sync
{
	import Common.Deleter;
	
	import Service.ServiceManager;
	
	import entity.Entity;
	import entity.EntityManager;
	import entity.EntityPlayer;
	 
	import flash.display.*;
	import flash.utils.ByteArray;
	
	import logic.GameLogic;
	
	public class Room implements IListener
	{
		private var startButton:SimpleButton = null;
		
		public function Room()
		{
		}
		
		public function onServerConnected():void
		{
			SyncSystem.getInstance().beginSendMsg(ConstValue.MSG_ID_REG_PLAYER);
			SyncSystem.getInstance().endSendMsg();
			
			EntityManager.getInstance().createStartButton();
		}
		
		public function onServerClosed():void{}
		
		public function onSocketError():void{}
		
		public function onServerMessage(netPackage:Stream):void
		{
			var gameLogic:GameLogic = GameLogic.getInstance();
			
			var msgType:int = netPackage.readInt();
			
			if (msgType == ConstValue.MSG_ID_CREATE_PLAYER)
			{
				var isSelf:int = netPackage.readInt();
				var playerNetID:int = netPackage.readInt();
				var posX:int = netPackage.readInt();
				var posY:int = netPackage.readInt();
				var isHost:int = netPackage.readInt();
				
				var handle:int = 0;
				var entityPlayer:EntityPlayer = null;
				
				if (isSelf != 0)
				{
					// 自己
					handle = EntityManager.getInstance().createEntity("player");
					entityPlayer = EntityManager.getInstance().getEntity(handle) as EntityPlayer;
					entityPlayer.setNetID(playerNetID);
					entityPlayer.x = posX;
					entityPlayer.y = posY;
					
					gameLogic.setSelfPlayerHandleID(handle);
					gameLogic.setIsHost(isHost);
										
				}
				else
				{
					// 其他人	
					handle = EntityManager.getInstance().createEntity("player");
					entityPlayer = EntityManager.getInstance().getEntity(handle) as EntityPlayer;
					entityPlayer.setNetID(playerNetID);
					entityPlayer.x = posX;
					entityPlayer.y = posY;
				}
			}
			else if (msgType == ConstValue.MSG_ID_DESTORY_PLAYER)
			{
				
			}
			else if (msgType == ConstValue.MSG_ID_START_SYNC)
			{
				EntityManager.getInstance().destroyStartButton();
				
				var syncSys:SyncSystem = SyncSystem.getInstance();
				syncSys.addListener(new Client);
			}
			else if (msgType == ConstValue.MSG_ID_PING)
			{
				GameLogic.getInstance().pong();
			}
			else if (msgType == ConstValue.MSG_ID_PLAYER_COUNT)
			{
				var count:int = netPackage.readInt();
				
				GameLogic.getInstance().setPlayerCount(count);
			}
		}
		
		public function step():void
		{
		}
		
		public function release():void
		{
		}
		
	}
}